package com.example.config;

import com.alibaba.fastjson.JSONObject;
import com.example.entity.User;
import com.example.utils.JwtUtil;
import com.example.utils.RedisUtil;
import com.example.utils.common.Constant;
import com.example.utils.common.PropertiesUtil;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;

public class CustomCache<K,V> implements Cache {

    private String getKey(Object key) {
        String claim = JwtUtil.getClaim(key.toString(), Constant.ACCOUNT);
//        User user = JSONObject.parseObject(claim, User.class);
        return Constant.PREFIX_SHIRO_CACHE +claim;
    }

    @Override
    public Object get(Object key) throws CacheException {
        if(Boolean.FALSE.equals(RedisUtil.exists(this.getKey(key)))){
            return null;
        }
        return JSONObject.parseObject(RedisUtil.get(this.getKey(key)), SimpleAuthorizationInfo.class);
    }

    @Override
    public Object put(Object key, Object value) throws CacheException {
        PropertiesUtil.readProperties("application.properties");
        String shiroCacheExpireTime = PropertiesUtil.getProperty("shiro.config.shiroCacheExpireTime");
        RedisUtil.set(this.getKey(key), JSONObject.toJSONString(value), Integer.parseInt(shiroCacheExpireTime));
        return value;
    }

    /**
     * 移除缓存
     */
    @Override
    public Object remove(Object key) throws CacheException {
        if(Boolean.FALSE.equals(RedisUtil.exists(this.getKey(key)))){
            return null;
        }
        RedisUtil.delete(this.getKey(key));
        return null;
    }

    /**
     * 清空所有缓存
     */
    @Override
    public void clear() throws CacheException {
        RedisUtil.clear();
    }

    /**
     * 缓存的个数
     */
    @Override
    public int size() {
        Set<String> keys = RedisUtil.keys("*");
        return keys!=null?keys.size():0;
    }

    /**
     * 获取所有的key
     */
    @Override
    public Set keys() {
        Set<String> keys = RedisUtil.keys("*");
        return keys;
    }

    /**
     * 获取所有的value
     */
    @Override
    public Collection values() {
        Set keys = this.keys();
        List<Object> values = new ArrayList<Object>();
        for (Object key : keys) {
            values.add(JSONObject.parseObject(RedisUtil.get(key.toString())));
        }
        return values;
    }
}
